package com.xkstream.client.ui.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessageExtension;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.xkstream.client.R;
import com.xkstream.client.nim.GifAttachment;
import com.xkstream.client.entity.ReceiveGift;
import com.xkstream.client.nim.WinAttachment;

import java.util.List;

/**
 * Created by admin on 2016/9/22.
 */
public class ChatRoomAdapter extends BaseAdapter {
    private List<Object> messages;
    private List<ReceiveGift> gifts;

    private Context context;
    //TYPE值不能小于VIEW ITEM COUNT  否则报数组越界
    private final static int DEFAULT_MSG_TYPE = 0;
    private final static int MSG_GIFT_TYPE = 1;
    private final static int INIT_MSG_TYPE = 2;
    private final static int NOTIFICATION_MSG_TYPE = 3;
    private final static int MSG_WIN_TYPE = 4;

    private CommentOnClickListener listener;

    public ChatRoomAdapter(List<Object> messages, List<ReceiveGift> gifts, Context context, CommentOnClickListener listener) {
        this.messages = messages;
        this.context = context;
        this.listener = listener;
        this.gifts = gifts;
    }

    public ChatRoomAdapter(List<Object> messages, Context context) {
        this.messages = messages;
        this.context = context;
    }

    @Override
    public int getCount() {
        return messages.size();
    }

    @Override
    public int getItemViewType(int position) {
        Object object = messages.get(position);
        if (object instanceof IMMessage) {
            IMMessage message = (IMMessage) object;
            MsgTypeEnum msgType = message.getMsgType();
            MsgAttachment attachment = message.getAttachment();
            if (attachment instanceof GifAttachment) {
                return MSG_GIFT_TYPE;
            } else if (msgType == MsgTypeEnum.notification) {
                return NOTIFICATION_MSG_TYPE;
            } else if (attachment instanceof WinAttachment) {
                return MSG_WIN_TYPE;
            } else {
                return DEFAULT_MSG_TYPE;
            }
        } else {
            return INIT_MSG_TYPE;
        }
    }

    @Override
    public int getViewTypeCount() {
        return 5;
    }

    @Override
    public Object getItem(int position) {
        return messages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent) {
        MessageViewHolder messageHolder;
        GifViewHolder giftHolder;
        InitViewHolder initViewHolder;
        NotificationViewHolder notificationViewHolder = null;
        WinViewHolder winViewHolder = null;
        int type = getItemViewType(position);
        if (v == null) {
            switch (type) {
                case INIT_MSG_TYPE:
                    initViewHolder = new InitViewHolder();
                    v = View.inflate(context, R.layout.layout_chatroom_init_item, null);
                    initViewHolder.tvInit = (TextView) v.findViewById(R.id.tvInit);
                    v.setTag(initViewHolder);
                    break;
                case DEFAULT_MSG_TYPE:
                    messageHolder = new MessageViewHolder();
                    v = View.inflate(context, R.layout.layout_chatroom_chat_item, null);
                    messageHolder.tvMessage = (TextView) v.findViewById(R.id.tvMessage);
                    messageHolder.ivLevel = (ImageView) v.findViewById(R.id.ivLevel);
                    v.setTag(messageHolder);
                    break;
                case MSG_GIFT_TYPE:
                    giftHolder = new GifViewHolder();
                    v = View.inflate(context, R.layout.layout_chatroom_gift_item, null);
                    giftHolder.tvGifMessage = (TextView) v.findViewById(R.id.tvGifMessage);
//                    giftHolder.tvGiftNum = (TextView) v.findViewById(R.id.tvGiftNum);
//                    giftHolder.tvNickName = (TextView) v.findViewById(R.id.tvNickName);
                    v.setTag(giftHolder);
                    break;
                case NOTIFICATION_MSG_TYPE:
                    notificationViewHolder = new NotificationViewHolder();
                    v = View.inflate(context, R.layout.layout_chatroom_noti_item, null);
                    notificationViewHolder.tvNotification = (TextView) v.findViewById(R.id.tvNotification);
                    notificationViewHolder.ivImg1 = (ImageView) v.findViewById(R.id.ivImg1);
                    notificationViewHolder.ivImg2 = (ImageView) v.findViewById(R.id.ivImg2);
                    v.setTag(notificationViewHolder);
                    break;
                case MSG_WIN_TYPE:
                    winViewHolder = new WinViewHolder();
                    v = View.inflate(context, R.layout.layout_chatroom_gift_item, null);
                    winViewHolder.tvContent = (TextView) v.findViewById(R.id.tvGifMessage);
                    v.setTag(winViewHolder);
                    break;
            }
        }
        Object holder = v.getTag();
        Object object = messages.get(position);

        if (holder instanceof MessageViewHolder) {
            final ChatRoomMessage message = (ChatRoomMessage) object;
            messageHolder = (MessageViewHolder) holder;
            ChatRoomMessageExtension extension = message.getChatRoomMessageExtension();
            //判断用户是不是null  如果不为NULL并且extension为NULL  则为自己发送
            // TODO 暂时没加用户判断

            //      User user = UserProxy.getUser();
            String account = message.getFromAccount();
            String nickName;
            if (extension == null) {
                //               messageHolder.tvNickName.setText(user.getNickname() + " : ");
                nickName = "我自己";
            } else {
                //                 messageHolder.tvNickName.setText(message.getChatRoomMessageExtension().getSenderNick() + " : ");
                nickName = message.getChatRoomMessageExtension().getSenderNick();
            }
            // TODO 点击评论
            messageHolder.tvMessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.commentHandle(message.getFromAccount());
                }
            });
            String strMessage = nickName + " : " + message.getContent();
            int num = getGiftRankNum(message.getFromAccount());
            if (num == 1) {
                messageHolder.tvMessage.setTextColor(context.getResources().getColor(R.color.orange_fd9c00));
                messageHolder.ivLevel.setImageDrawable(context.getResources().getDrawable(R.drawable.crown_first));
                messageHolder.ivLevel.setVisibility(View.VISIBLE);
            } else if (num == 2) {
                messageHolder.tvMessage.setTextColor(context.getResources().getColor(R.color.orange_fd9c00));
                messageHolder.ivLevel.setImageDrawable(context.getResources().getDrawable(R.drawable.crown_first));
                messageHolder.ivLevel.setVisibility(View.VISIBLE);
            } else if (num == 3) {
                messageHolder.tvMessage.setTextColor(context.getResources().getColor(R.color.orange_fd9c00));
                messageHolder.ivLevel.setImageDrawable(context.getResources().getDrawable(R.drawable.crown_first));
                messageHolder.ivLevel.setVisibility(View.VISIBLE);
            } else {
                messageHolder.tvMessage.setTextColor(context.getResources().getColor(R.color.green_78ff00));
                messageHolder.ivLevel.setVisibility(View.GONE);
            }
//            ForegroundColorSpan fontColor = new ForegroundColorSpan(context.getResources().getColor(R.color.white));
//            ForegroundColorSpan nameColor = new ForegroundColorSpan(context.getResources().getColor(R.color.white));
//            SpannableStringBuilder builder = new SpannableStringBuilder(nickName + " : " + strMessage);
//            builder.setSpan(nameColor, 0, (nickName + " : ").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//            builder.setSpan(fontColor, (nickName + " : ").length(), (nickName + " : " + strMessage).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            messageHolder.tvMessage.setText(strMessage);
        } else if (holder instanceof GifViewHolder) {
            giftHolder = (GifViewHolder) holder;
            final IMMessage message = (IMMessage) object;
            final GifAttachment attcachment = (GifAttachment) message.getAttachment();
            String strGiftMessage;
            String senderName = attcachment.getSenderName() + " :  ";
            String giftName = "送给主播1个" + attcachment.getGiftName();
            String giftNumStr = "";
            if (!TextUtils.isEmpty(attcachment.getGiftNum()+"")) {
                int giftNum = (attcachment.getGiftNum());
                if (giftNum > 1) {
                    giftNumStr = "  " + attcachment.getGiftNum() + "连击！";
                    //                 giftHolder.tvGiftNum.setText(attcachment.getGiftNum() + "连击！");
                }
            }
            giftHolder.tvGifMessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.commentHandle(attcachment.getSenderID());
                }
            });
            strGiftMessage = senderName + giftName + giftNumStr;
            SpannableStringBuilder builder = new SpannableStringBuilder(strGiftMessage);
            ForegroundColorSpan messageColor = new ForegroundColorSpan(context.getResources().getColor(R.color.orange_fff000));
            ForegroundColorSpan giftNumColor = new ForegroundColorSpan(context.getResources().getColor(R.color.bg_gray));
            builder.setSpan(messageColor, 0, (senderName + giftName).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(giftNumColor, (senderName + giftName).length(), strGiftMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), (senderName + giftName).length(), strGiftMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            giftHolder.tvGifMessage.setText(builder);
        } else if (holder instanceof InitViewHolder) {
            String tip = object.toString();
            initViewHolder = (InitViewHolder) holder;
            initViewHolder.tvInit.setText(tip);
        } else if (holder instanceof NotificationViewHolder) {
            notificationViewHolder = (NotificationViewHolder) holder;
            ChatRoomMessage message = (ChatRoomMessage) object;
            ChatRoomNotificationAttachment attachment = (ChatRoomNotificationAttachment) message.getAttachment();
            NotificationType messgeType = attachment.getType();
//            if (messgeType == NotificationType.ChatRoomMemberExit) {
//                String nickname = attachment.getOperatorNick();
//                String strExit = "用户  " + attachment.getOperatorNick() + "  退出直播间";
//                ForegroundColorSpan fontColor = new ForegroundColorSpan(context.getResources().getColor(R.color.black));
//                ForegroundColorSpan nameColor = new ForegroundColorSpan(context.getResources().getColor(R.color.black));
//                SpannableStringBuilder builder = new SpannableStringBuilder(strExit);
//                builder.setSpan(fontColor, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                builder.setSpan(nameColor, 4, nickname.length() + 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                builder.setSpan(fontColor, nickname.length() + 6, strExit.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                notificationViewHolder.tvNotification.setText(builder);
//            } else

            String nickName = attachment.getOperatorNick();
            if (TextUtils.isEmpty(nickName)) {
                nickName = "自己";
            }
            if (messgeType == NotificationType.ChatRoomMemberIn) {
                String strJoin = context.getResources().getString(R.string.welcome_enter_room, nickName);
                notificationViewHolder.tvNotification.setText(strJoin);
                notificationViewHolder.ivImg1.setImageDrawable(context.getResources().getDrawable(R.drawable.welcome));
                notificationViewHolder.ivImg2.setImageDrawable(context.getResources().getDrawable(R.drawable.welcome));
                notificationViewHolder.ivImg1.setVisibility(View.VISIBLE);
                notificationViewHolder.ivImg2.setVisibility(View.VISIBLE);
                notificationViewHolder.tvNotification.setTextColor(context.getResources().getColor(R.color.green_78ff00));
            } else if (messgeType == NotificationType.ChatRoomManagerAdd) {
                //设为房管
                String strCongratulation = "恭喜 “" + attachment.getTargetNicks().get(0) + "”成为房管，大家热烈祝贺！";
                notificationViewHolder.ivImg2.setVisibility(View.VISIBLE);
                notificationViewHolder.ivImg1.setVisibility(View.GONE);
                notificationViewHolder.ivImg2.setImageDrawable(context.getResources().getDrawable(R.drawable.congratulation));
                notificationViewHolder.tvNotification.setTextColor(context.getResources().getColor(R.color.violet_ff41ba));
                notificationViewHolder.tvNotification.setText(strCongratulation);
            } else if (messgeType == NotificationType.ChatRoomMemberTempMuteAdd) {
                //临时禁言
                if (attachment.getTargetNicks().size() > 0) {
                    nickName = attachment.getTargetNicks().get(0);
                }
                String strShutUp = "“" + attachment.getTargetNicks().get(0) + "”被禁言24小时";
                notificationViewHolder.ivImg2.setVisibility(View.VISIBLE);
                notificationViewHolder.ivImg1.setVisibility(View.GONE);
                notificationViewHolder.ivImg2.setImageDrawable(context.getResources().getDrawable(R.drawable.shutup));
                notificationViewHolder.tvNotification.setText(strShutUp);
                notificationViewHolder.tvNotification.setTextColor(context.getResources().getColor(R.color.red_ff2121));
            } else if (messgeType == NotificationType.ChatRoomManagerRemove) {
                //解除房管
                String strChexiao = "真可惜，“" + attachment.getTargetNicks().get(0) + "”被主播撤销房管";
                notificationViewHolder.ivImg2.setVisibility(View.VISIBLE);
                notificationViewHolder.ivImg1.setVisibility(View.GONE);
                notificationViewHolder.tvNotification.setText(strChexiao);
                notificationViewHolder.ivImg2.setImageDrawable(context.getResources().getDrawable(R.drawable.so_said));
                notificationViewHolder.tvNotification.setText(strChexiao);
                notificationViewHolder.tvNotification.setTextColor(context.getResources().getColor(R.color.blue_9cd4ff));

            }
        } else if (holder instanceof WinViewHolder) {
            StringBuilder builder = new StringBuilder("恭喜");
            ChatRoomMessage message = (ChatRoomMessage) object;
            WinAttachment attachment = (WinAttachment) message.getAttachment();
            builder.append(attachment.getUserNickName())
                    .append("赢得了")
                    .append(attachment.getProfit())
                    .append("元");
            ((WinViewHolder) holder).tvContent.setText(builder.toString());
            ((WinViewHolder) holder).tvContent.setTextColor(Color.parseColor("#ffb82e"));
        }
        return v;
    }

    private int getGiftRankNum(String userAccount) {
        for (int i = 0; i < gifts.size(); i++) {
            if (gifts.get(0).getSend_user_code().equals(userAccount)) {

                return 1;
            }
            if (gifts.size() >= 2) {
                if (gifts.get(1).getSend_user_code().equals(userAccount)) {
                    return 2;
                }
            }
            if (gifts.size() >= 3) {
                if (gifts.get(2).getSend_user_code().equals(userAccount)) {
                    return 3;
                }
            }

        }
        return 0;
    }

    private class MessageViewHolder {
        TextView tvMessage;
        ImageView ivLevel;
    }

    private class GifViewHolder {
        TextView tvGifMessage;
//        TextView tvGiftName;
//        TextView tvGiftNum;
    }

    private class InitViewHolder {
        TextView tvInit;
    }

    private class NotificationViewHolder {
        TextView tvNotification;
        ImageView ivImg1;
        ImageView ivImg2;
    }

    private static class WinViewHolder {
        TextView tvContent;
    }


    public interface CommentOnClickListener {
        void commentHandle(String userId);
    }
}
